<template>
  <div class="login">
    <h2>叩丁狼商品管理系统</h2>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      class="demo-ruleForm"
    >
      <el-form-item prop="username">
        <el-input
          v-model="ruleForm.username"
          autocomplete="off"
          :prefix-icon="Avatar"
          size="large"
          placeholder="请输入账号"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="ruleForm.password"
          type="password"
          autocomplete="off"
          :prefix-icon="Lock"
          size="large"
          placeholder="请输入密码"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Avatar, Lock } from "@element-plus/icons-vue";
import { user } from "@/api";
import { useRouter } from "vue-router";
import { useUserStore } from "@/store";

const router = useRouter();
const userState = useUserStore();
const ruleFormRef = ref<FormInstance>();

const validatePass = (rule: any, value: string, callback: any) => {
  if (value === "") {
    // 如果不通过校验，需要 callback里面传入一个错误对象
    callback(new Error("账号不能为空"));
  } else {
    // 校验通过，就直接调用 callback就行
    callback();
  }
};
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("Please input the password again"));
  } else {
    callback();
  }
};

const ruleForm = reactive({
  username: "",
  password: "",
});

const rules = reactive({
  username: [{ validator: validatePass, trigger: "blur" }],
  password: [{ validator: validatePass2, trigger: "blur" }],
});

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    // 如果校验不通过
    if (!valid) {
      return false;
    }
    // 向服务器发请求
    user.loginApi(ruleForm).then((res) => {
      if (res.code === 200) {
        // 存储token，进行拼接
        localStorage.setItem("token", res.data.tokenHead + res.data.token);
        // 提示弹框
        ElMessage.success("登录成功");
        // 跳转到首页
        router.push("/index");
      }
    });
  });
};
</script>

<style scoped>
.login {
  width: 400px;
  margin: 150px auto;
}

h2 {
  text-align: center;
}

.el-button {
  width: 100%;
}

:deep(.el-input__wrapper) {
  background-color: transparent;
}

:deep(.el-input__inner) {
  color: #fff;
}
</style>
